import streamlit as st
# 使用标准的Python日志记录模块
# import logging
import os
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)
# logger.info("应用启动")
domain_name=os.getenv("GATEWAY","kubesre.xyz")


# 定义源仓库到目标仓库的映射表
repo_mapping = {
    "cr.l5d.io": f"l5d.{domain_name}",
    "docker.elastic.co": f"elastic.{domain_name}",
    "docker.io": f"docker.{domain_name}",
    "gcr.io": f"gcr.{domain_name}",
    "ghcr.io": f"ghcr.{domain_name}",
    "k8s.gcr.io": f"k8s-gcr.{domain_name}",
    "registry.k8s.io": f"k8s.{domain_name}",
    "mcr.microsoft.com": f"mcr.{domain_name}",
    "nvcr.io": f"nvcr.{domain_name}",
    "quay.io": f"quay.{domain_name}",
    "registry.jujucharms.com": f"jujucharms.{domain_name}"
}

# 默认的Docker Hub仓库地址
default_repo = "docker.io"

def get_proxy_repo(source_repo):
    # 拆分仓库地址和标签
    parts = source_repo.split('/')
    repo_name = parts[0] if len(parts) > 1 else default_repo
    image_name = '/'.join(parts[1:]) if len(parts) > 1 else parts[0]

    # 根据映射表获取目标仓库地址
    target_repo = repo_mapping.get(repo_name, repo_mapping[default_repo])

    # 构建并返回完整的目标仓库地址
    return f"{target_repo}/{image_name}"
markdown_content = """
<div align="center">
{0}
</div>
"""
def main():
    # 设置页面的标题
    st.set_page_config(
        page_title="Docker Proxy",
        page_icon="👋",
    )
    # 导航栏（这里只是展示，Streamlit没有内置的导航栏功能）
    # st.sidebar.title("导航")
    # st.sidebar.write("这里可以添加导航链接或按钮")

    # 介绍部分
    with st.container():
        st.markdown(markdown_content.format("<h1>Docker Proxy</h1>"),unsafe_allow_html=True)
        st.markdown(markdown_content.format("多平台容器镜像代理服务,支持 Docker Hub, GitHub, Google, k8s, Quay, Microsoft 等镜像仓库."),unsafe_allow_html=True)
        # st.markdown(markdown_content.format("本站来源于:[docker-registry-mirrors](https://github.com/kubesre/docker-registry-mirrors)"),unsafe_allow_html=True)
        st.markdown(markdown_content.format("本站来源于:<a href=\"https://github.com/kubesre/docker-registry-mirrors\">docker-registry-mirrors</a>"),unsafe_allow_html=True)


        # st.write("多平台容器镜像代理服务,支持 Docker Hub, GitHub, Google, k8s, Quay, Microsoft 等镜像仓库.")
        # st.markdown(markdown_content.format("<h2><a href=\"https://www.example.com\">ℹ️使用文档</a></h2>"),unsafe_allow_html=True)

        # st.markdown("本站来源于:[docker-registry-mirrors](https://github.com/kubesre/docker-registry-mirrors)")
        # st.markdown(markdown_content.format("本站来源于:[docker-registry-mirrors](https://github.com/kubesre/docker-registry-mirrors)"),unsafe_allow_html=True)

        # st.markdown("## 🏊 快捷命令")
        st.markdown(markdown_content.format("<h2>快捷命令</h2>"),unsafe_allow_html=True)

    # 表单部分
    with st.form("docker_form"):
        # 第一步：输入原始镜像地址
        source_image = st.text_input("第一步：输入原始镜像地址", "stilleshan/frpc:latest")

        # 获取命令按钮
        submitted = st.form_submit_button("获取命令")
        st.markdown("### 适用于将镜像拉取到本地的命令")
        target_image = st.empty()
        rename_image = st.empty()
        rm_image = st.empty()
        st.markdown("### 适用于替换文件中镜像的命令")
        update_image_file = st.empty()
        # 添加JavaScript统计代码
        st.markdown("""
        <script>
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?ead1ad43aa1e68d7d4c415e119be8b17"; 
          var s = document.getElementsByTagName("script")[0]; 
          s.parentNode.insertBefore(hm, s);
        })();
        </script>
        """, unsafe_allow_html=True)
        # target_image = st.text_input("第二步：代理拉取镜像","kubesre.xyz/stilleshan/frpc:latest")
        # rename_image = st.text_input("第三步：重命名镜像","docker tag kubesre.xyz/stilleshan/frpc:latest")
        # rm_image = st.text_input("第四步：删除代理镜像","docker rmi kubesre.xyz/stilleshan/frpc:latest")
        target_image.text_input("第二步：代理拉取镜像","docker pull docker.kubesre.xyz/stilleshan/frpc:latest",disabled=True)
        rename_image.text_input("第三步：重命名镜像","docker tag kubesre.xyz/stilleshan/frpc:latest",disabled=True)
        rm_image.text_input("第四步：删除代理镜像","docker rmi kubesre.xyz/stilleshan/frpc:latest",disabled=True)
        update_image_file.text_input("替换文件中的镜像","sed -i \"s#stilleshan/frpc:latest#kubesre.xyz/stilleshan/frpc:latest#g\" 你的文件名",disabled=True)
        if submitted:
            # 根据输入生成加速仓库的镜像地址
            # 获取代理仓库地址
            proxy_image = get_proxy_repo(source_image)
            proxy_image_cmd = f"docker pull {proxy_image}"
            tag_image = f"docker tag {proxy_image} {source_image}"
            remove_image = f"docker rmi {proxy_image}"
            sed_image = f"sed -i \"s#{source_image}#{proxy_image}#g\" 你的文件名"
            # 创建占位符

            target_image.text_input("第二步：代理拉取镜像",proxy_image_cmd)
            # # 更新占位符内容
            rename_image.text_input("第三步：重命名镜像",tag_image)
            # placeholder2.markdown(f"第三步：重命名镜像\n`{tag_image}`")
            rm_image.text_input("第四步：删除代理镜像",remove_image)
            update_image_file.text_input("替换文件中的镜像",sed_image)

if __name__ == "__main__":
    main()